#include "EnemiesManager.h"

#define PI 3.14159265

EnemiesManager::EnemiesManager(TMXLoader m)
{
    map = m;
    image = new CSprite();
    image->loadSpriteSparrowXML("data/img/game-enemy.xml");


    createEnemy(10, 4);
    createEnemy(15, 4);
    createEnemy(20, 4);
    createEnemy(25, 4);
    createEnemy(29, 4);

    createEnemy(27, 9);
    createEnemy(27, 14);
    createEnemy(27, 19);
    createEnemy(27, 24);
    createEnemy(27, 29);

    createEnemy(22, 24);
    createEnemy(22, 29);
    createEnemy(17, 24);
    createEnemy(17, 29);
    createEnemy(12, 24);
    createEnemy(12, 29);
    createEnemy(7, 24);
    createEnemy(7, 29);

    createEnemy(13, 12);
    createEnemy(13, 18);
    createEnemy(5, 13);
    createEnemy(5, 17);
}

EnemiesManager::~EnemiesManager()
{
    //dtor
}


std::vector<Kinematic>* EnemiesManager::getEnemies()
{
    return &enemies;
}



void EnemiesManager::draw()
{
    for(int i = 0; i < enemies.size(); i++)
    {
        image->setPosition(enemies.at(i).pos.X, enemies.at(i).pos.Y);
        image->setRotation(getAngle(enemies.at(i).pos) + 90);
        image->draw();
    }
}


void EnemiesManager::createEnemy(float x, float y)
{
    float xe, ye;
    Kinematic enemy;
    enemy.maxSpeed = 4;
    map.getCenter(x,y, xe, ye);
    enemy.pos.X = xe;
    enemy.pos.Y = ye;
    enemies.push_back(enemy);
}

bool EnemiesManager::hitTest(irrklang::vec3df& pos, float width, float height)
{
    float distance = 0;
    irrklang::vec3df center = pos;
    irrklang::vec3df centerEnemy;
    center.X += width/2;
    center.Y += height/2;

    for(int i = 0; i < enemies.size(); i++)
    {
        centerEnemy = enemies.at(i).pos;
        centerEnemy.X += 16;
        centerEnemy.Y += 16;

        distance = center.getDistanceFrom(centerEnemy);

        if(distance < width/2)
        {
            return true;
        }
    }
    return false;
}

void EnemiesManager::setPlayerPos(irrklang::vec3df pos)
{
    playerPos = pos;
}

float EnemiesManager::getAngle(irrklang::vec3df posEnemy)
{
    irrklang::vec3df up;
    up.X = 0;
    up.Y = 1;
    irrklang::vec3df normal;

    float dotProduct;

    normal = playerPos - posEnemy;
    normal = normal.normalize();

    dotProduct = normal.dotProduct(up);
    float angle = (acos(dotProduct) * (180.0 / PI));

    if(playerPos.X > posEnemy.X)
        angle = -angle;

    return angle;
}
